package dao

import (
	"context"
	"core/models/db"
	"core/models/entity"
	"core/repo"
	"go.mongodb.org/mongo-driver/bson"
)

type RealDao struct {
	repo *repo.Manager
}

func (d *RealDao) FindRealByUid(ctx context.Context, uid uint) *db.UserRealName {
	userReal := new(db.UserRealName)
	d.repo.DB.Client.WithContext(ctx).Table(userReal.TableName()).Where("uid=?", uid).First(userReal)
	return userReal
}

func (d *RealDao) RealCard(ctx context.Context, card string) int64 {
	realName := new(db.UserRealName)
	var count int64
	d.repo.DB.Client.WithContext(ctx).Model(realName).Where("id_card=?", card).Count(&count)
	return count
}
func (d *RealDao) AddReal(ctx context.Context, realName *db.UserRealName) (uint, error) {
	err := d.repo.DB.Client.WithContext(ctx).Model(realName).Create(realName).Error
	if err != nil {
		return 0, err
	}
	return realName.ID, nil
}

func (d *RealDao) MongoUpUserReal(ctx context.Context, uid uint, msg entity.RealMsg) error {
	collection := d.repo.Mongo.Db.Collection("user")
	_, err := collection.UpdateOne(ctx, bson.M{
		"uid": uid,
	}, bson.M{
		"$set": bson.M{
			"realMsg": msg,
		},
	})
	return err
}

func NewRealDao(m *repo.Manager) *RealDao {
	return &RealDao{
		repo: m,
	}
}
